package com.chongyahhh.security.security.evaluator;

import com.chongyahhh.security.security.authority.PermissionGrantedAuthority;
import com.chongyahhh.security.security.authority.PermissionUnit;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

/**
 * @Author chongyahhh
 * 注解权限验证
 */
@Component
public class RolePermissionEvaluator implements PermissionEvaluator {

    /**
     * @PreAuthorize("hasPermission('/user/listUser', 'listUser')")
     * @param authentication 用户信息，包括权限列表
     * @param url 对应注解中的 /user/listUser
     * @param permission 对应注解中的 listUser
     * @return
     */
    @Override
    public boolean hasPermission(Authentication authentication, Object url, Object permission) {
        //AtomicBoolean hasPermission = new AtomicBoolean(false);
        // 先获取权限
        Set<GrantedAuthority> roles = new HashSet<>(authentication.getAuthorities());
        // 判断是否有权限
        for(GrantedAuthority r : roles){
            // 如果 r 不是 PermissionGrantedAuthority 的实例，就说明现在没有登录，
            // 用户信息是 Spring Security 添加的匿名用户（AnonymousAuthenticationFilter）
            if (r instanceof PermissionGrantedAuthority) {
                PermissionGrantedAuthority rn = (PermissionGrantedAuthority) r;
                for(PermissionUnit p : rn.getPermissions()){
                    if (p.getPermission().equals(permission) && p.getUrl().equals(url)) {
                        return true;
                    }
                }
            }
        }

        return false;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable serializable, String s, Object o) {
        return false;
    }
}
